package com.ruoyi.project.common;
import com.alibaba.druid.stat.JdbcSqlStat;
import org.json.JSONObject;
//import com.alibaba.fastjson.JSONObject;
import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.Map;
@CrossOrigin
public class RequestDemo {
//    public static void main(String[] args) {
//        RequestDemo.getAuth();
//        String text="上海市浦东新区纳贤路701号百度上海研发中心 F4A000 张三";
//        RequestDemo.getText(text);
//
//    }
        public static String getAuth(){
            String path = "https://aip.baidubce.com/oauth/2.0/token";
            ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);


            // 设置header参数
            request.addHeaderParameter("Content-Type", "application/json; charset=utf-8");

            // 设置query参数
            request.addQueryParameter("grant_type", "client_credentials");
            request.addQueryParameter("client_id", "rmqZsRNQiSNmNN5tgmiI0WtZ");
            request.addQueryParameter("client_secret", "12AiObdnIHVzXkVDaN214NnKEQNUcMEE");
            ApiExplorerClient client = new ApiExplorerClient();

            try {
                ApiExplorerResponse response =client.sendRequest(request);
                        // 返回结果格式为Json字符串

                JSONObject jsonObject = new JSONObject(response.getResult());
                String access_token = jsonObject.getString("access_token");
                return access_token;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
    }

    public static String getText(String text){
        String path = "https://aip.baidubce.com/rpc/2.0/nlp/v1/address";
        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.POST, path);


        // 设置header参数
        request.addHeaderParameter("Content-Type", "application/json;charset=UTF-8");

        String token = RequestDemo.getAuth();
        // 设置query参数
        request.addQueryParameter("access_token", token);
        request.addQueryParameter("text", text);
        ApiExplorerClient client = new ApiExplorerClient();

        try {
            ApiExplorerResponse response = client.sendRequest(request);
            // 返回结果格式为Json字符串
//            JSONObject jsonObject = JSONObject.parseObject(String.valueOf(response));
//            System.out.println(jsonObject);
//            String access_token = jsonObject.getString("access_token");
//            System.out.println(access_token);
            String result = response.getResult();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
